//
//  ZhaoPinViewController.m
//  HubeiHotel
//
//  Created by LiBenCan on 17/11/16.
//  Copyright © 2017年 张露杰. All rights reserved.
//

#import "ZhaoPinViewController.h"
#import "WokerViewController.h"

#import "HBHMainSearchHistoryCell.h"
#import "HBHMainResumeCell.h"
#import "HBHMainBusinessCell.h"
#import "HBHMainHotelCell.h"
#import "CompanyCell.h"

#import "HBHChouseTypeView.h"
#import "CCSDSortView.h"
#import "CCSDChouseKindView.h"
#import "HBHChouseAreaView.h"
#import "HBHChousePositionView.h"
#import "HBHChouseCamponyView.h"
#import "HBHChouseTypeView.h"

@interface ZhaoPinViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,BMKLocationServiceDelegate>
{
    NSMutableArray *_titles;
}

@property (nonatomic, strong) UITableView *table;
@property (nonatomic, strong) CCSDSortView *allSortView;
@property (nonatomic, strong) CCSDSortView *togetherSortView;
@property (nonatomic, strong) CCSDSortView *brandSortView;

@property (nonatomic, retain) NSMutableArray *datas;
@property (nonatomic) NSInteger pageNo;
@property (nonatomic, retain) NSDictionary *tradingArea;
@property (nonatomic, retain) NSDictionary *area;

@property (nonatomic, retain) NSDictionary *jobDictValue;
@property (nonatomic, retain) NSDictionary *companyDictValue;
@property (nonatomic, retain) NSDictionary *desired_income;
@property (nonatomic, retain) NSDictionary *working_life;
@property (nonatomic, retain) NSDictionary *education;
@property (nonatomic, retain) NSDictionary *job_type;
@property (nonatomic, retain) NSDictionary *field;
@property (nonatomic, retain) NSDictionary *phase;
@property (nonatomic, copy) NSString *keyWord;

/**
 定位类
 */
@property (nonatomic, strong) BMKLocationService *locService;

/**
 用户位置
 */
@property (nonatomic, strong) BMKUserLocation *userLocation;

@end

@implementation ZhaoPinViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initSearchBarWithPlaceholder:@"请输入关键字搜索" showsCancelButton:NO];
    _datas = [NSMutableArray new];
    _pageNo = 1;
    _keyWord = @"";
    [self creatView];
    
    if (![TomamaUI isEnabledLocationServices]) {
        [TomamaUI openGPS];
    }
    [HudHelper showProgressHudWithMessage:@"" toView:self.view];
    [self.locService startUserLocationService];
    [self getJobDictValue];
    [self getCompanyDictValue];
}

-(void)creatView
{
    _titles = @[@"全部",@"职位筛选",@"公司筛选"].mutableCopy;
//    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//    btn.frame = CGRectMake(0, 0, 44, 44);
//    [btn addTarget:self action:@selector(onTapLeftBarButton) forControlEvents:UIControlEventTouchUpInside];
////    [btn addSubview:[TomamaUI createImageView:CGRectMake(0, 0, 9*screenW_6, 15*screenW_6) backGroundImageV:@"back"]];
//    [btn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
//    UIBarButtonItem *barButtonitem = [[UIBarButtonItem alloc] initWithCustomView:btn];
//    self.navigationItem.leftBarButtonItem = barButtonitem;
    
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, 40*screenW_6)];
    topView.backgroundColor = TextWhite;
    [self.view addSubview:topView];
    [topView addSubview:self.allSortView];
    [topView addSubview:self.togetherSortView];
    [topView addSubview:self.brandSortView];
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 40*screenW_6 - 1, SCREENW, 1)];
    lineView.backgroundColor = backColor;
    [topView addSubview:lineView];
    
    for (int i = 0; i < 2; i++) {
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(114.5*screenW_6 + (SCREENW - 230*screenW_6)*i, 0, 1, 14*screenW_6)];
        lineView.backgroundColor = [UIColor colorWithHexString:@"#e5e5e5"];
        [topView addSubview:lineView];
        lineView.center = CGPointMake(lineView.center.x, topView.frame.size.height/2);
    }
    
    [self.view addSubview:self.table];
}

#pragma mark - BMKLocationService
-(BMKLocationService *)locService
{
    if (!_locService) {
        _locService = [[BMKLocationService alloc]init];
        _locService.delegate = self;
    }
    return _locService;
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    _userLocation = userLocation;
    if (_userLocation) {
        [self.locService stopUserLocationService];
        [self getDatas];
    }
}

/**
 *定位失败后，会调用此函数
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}

-(CCSDSortView *)allSortView
{
    if (!_allSortView) {
        _allSortView = [[CCSDSortView alloc]initWithFrame:CGRectMake(0, 0, 115*screenW_6, 40*screenW_6) title:@"全部"];
        __weak typeof(self) weakSelf = self;
        _allSortView.chouseComplete = ^(){
            UIView *view1 = [weakSelf.view viewWithTag:101];
            UIView *view2 = [weakSelf.view viewWithTag:102];
            [view1 removeFromSuperview];
            [view2 removeFromSuperview];
            weakSelf.togetherSortView.isSelect = NO;
            [weakSelf.togetherSortView creatViewWithTitle:@"职位筛选"];
            weakSelf.brandSortView.isSelect = NO;
            [weakSelf.brandSortView creatViewWithTitle:@"公司筛选"];
            
            HBHChouseAreaView *view = [[HBHChouseAreaView alloc]initUserLocation:weakSelf.userLocation selectArea:weakSelf.area selectTradingArea:weakSelf.tradingArea complete:^(NSDictionary *area, NSDictionary *tradingArea) {
                weakSelf.area = area;
                weakSelf.tradingArea = tradingArea;
                [weakSelf changeSort];
            }];
            [view showOnView:weakSelf.view];
            
            view.disMissBlock = ^(){
                weakSelf.allSortView.isSelect = NO;
                [weakSelf.allSortView creatViewWithTitle:weakSelf.tradingArea[@"name"]];
            };
            [view showOnView:weakSelf.view];
            view.tag = 100;
        };
        
        _allSortView.unChouseComplete = ^(){
            UIView *view = [weakSelf.view viewWithTag:100];
            [view removeFromSuperview];
            [weakSelf.table reloadData];
        };
    }
    return _allSortView;
}

-(CCSDSortView *)togetherSortView
{
    if (!_togetherSortView)  {
        _togetherSortView = [[CCSDSortView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.allSortView.frame), 0, SCREENW - 230*screenW_6, 40*screenW_6) title:@"职位筛选"];
        __weak typeof(self) weakSelf = self;
        _togetherSortView.chouseComplete = ^(){
            UIView *view1 = [weakSelf.view viewWithTag:100];
            UIView *view2 = [weakSelf.view viewWithTag:102];
            [view1 removeFromSuperview];
            [view2 removeFromSuperview];
            
            weakSelf.allSortView.isSelect = NO;
            [weakSelf.allSortView creatViewWithTitle:weakSelf.tradingArea[@"name"]?weakSelf.tradingArea[@"name"]:@"全部"];
            weakSelf.brandSortView.isSelect = NO;
            [weakSelf.brandSortView creatViewWithTitle:@"公司筛选"];
            
            HBHChousePositionView *view = [[HBHChousePositionView alloc]initWithData:weakSelf.jobDictValue desired_income:weakSelf.desired_income working_life:weakSelf.working_life education:weakSelf.education job_type:weakSelf.job_type];
            
            view.blcok = ^(NSDictionary *desired_income,NSDictionary *working_life,NSDictionary *education,NSDictionary *job_type){
                weakSelf.desired_income = desired_income;
                weakSelf.working_life = working_life;
                weakSelf.education = education;
                weakSelf.job_type = job_type;
                [weakSelf changeSort];
            };
            view.dismissBlcok = ^(){
                weakSelf.togetherSortView.isSelect = NO;
                [weakSelf.togetherSortView creatViewWithTitle:@"职位筛选"];
            };
            [view showOnView:weakSelf.view];
            view.tag = 101;
        };
        
        _togetherSortView.unChouseComplete = ^(){
            UIView *view = [weakSelf.view viewWithTag:101];
            [view removeFromSuperview];
        };
    }
    return _togetherSortView;
}

-(CCSDSortView *)brandSortView
{
    if (!_brandSortView) {
        _brandSortView = [[CCSDSortView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.togetherSortView.frame), 0, 115*screenW_6, 40*screenW_6) title:@"公司筛选"];
        __weak typeof(self) weakSelf = self;
        _brandSortView.chouseComplete = ^(){
            UIView *view1 = [weakSelf.view viewWithTag:100];
            UIView *view2 = [weakSelf.view viewWithTag:101];
            [view1 removeFromSuperview];
            [view2 removeFromSuperview];
            
            weakSelf.allSortView.isSelect = NO;
            [weakSelf.allSortView creatViewWithTitle:weakSelf.tradingArea[@"name"]?weakSelf.tradingArea[@"name"]:@"全部"];
            weakSelf.togetherSortView.isSelect = NO;
            [weakSelf.togetherSortView creatViewWithTitle:@"职位筛选"];
            
            HBHChouseCamponyView *view = [[HBHChouseCamponyView alloc]initWithData:weakSelf.companyDictValue field:weakSelf.field phase:weakSelf.phase];
            view.blcok = ^(NSDictionary *field,NSDictionary *phase){
                weakSelf.field = field;
                weakSelf.phase = phase;
                [weakSelf changeSort];
            };
            view.dismissBlcok = ^(){
                weakSelf.brandSortView.isSelect = NO;
                [weakSelf.brandSortView creatViewWithTitle:@"公司筛选"];
            };
            [view showOnView:weakSelf.view];
            view.tag = 102;
        };
        
        _brandSortView.unChouseComplete = ^(){
            UIView *view = [weakSelf.view viewWithTag:102];
            [view removeFromSuperview];
            [weakSelf.table reloadData];
        };
    }
    return _brandSortView;
}

-(UITableView *)table
{
    if (!_table) {
        _table = [[UITableView alloc]initWithFrame:CGRectMake(0, 40*screenW_6, SCREENW, SCREENH - 64) style:UITableViewStylePlain];
        _table.delegate = self;
        _table.dataSource = self;
        _table.showsHorizontalScrollIndicator = NO;
        _table.showsVerticalScrollIndicator = NO;
        _table.separatorStyle = 0;
        _table.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        _table.backgroundColor = [UIColor clearColor];
        
        _table.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            _pageNo = 1;
            [_datas removeAllObjects];
            [self getDatas];
        }];
        //加载
        _table.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            _pageNo++;
            [self getDatas];
        }];
    }
    return _table;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return .1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5*screenW_6;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _datas.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        HBHMainResumeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HBHMainResumeCell"];
        if (!cell) {
            cell = [[HBHMainResumeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HBHMainResumeCell"];
        }
        [cell loadCellWithData:_datas[indexPath.section]];
         return cell;
    }else
    {
        CompanyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CompanyCell"];
        if (!cell) {
            cell = [[CompanyCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CompanyCell"];
        }
        [cell setDataDic:_datas[indexPath.section]];
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0){
        return 108*screenW_6;
    }else if (indexPath.row == 1){
        return 67.5*screenW_6;
    }
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section > _datas.count) {
        return;
    }
    WokerViewController *vc = [WokerViewController new];
    vc.wordId = _datas[indexPath.section][@"id"];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - @selector
-(void)deleteHistory
{
    [standfault removeObjectForKey:@"searchHistory"];
    [_table reloadData];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if (![TomamaUI isNotNullStr:[[searchBar.text componentsSeparatedByString:@" "] componentsJoinedByString:@""]]) {
        return;
    }
    [HudHelper showProgressHudWithMessage:@"" toView:self.view];
    [searchBar resignFirstResponder];
    [_datas removeAllObjects];
    [self getDatas];
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    HBHBackView *view;
    if ([self.view viewWithTag:100]) {
        view = (id)[self.view viewWithTag:100];
    }else{
        view = [[HBHBackView alloc] init];
        view.tag = 100;
    }
    view.blcok = ^(){
        [searchBar resignFirstResponder];
    };
    [self.view addSubview:view];
    return YES;
}

-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    UIView *view = [self.view viewWithTag:100];
    [view removeFromSuperview];
    _keyWord = searchBar.text;
    return YES;
}

#pragma mark - changeSort
-(void)changeSort
{
    [HudHelper showProgressHudWithMessage:@"" toView:self.view];
    _pageNo = 1;
    [_datas removeAllObjects];
    [_table.mj_footer resetNoMoreData];
    [self getDatas];
}

#pragma mark - request
-(void)getDatas
{
    NSString *area = @"";
    if (_tradingArea) {
        area = _tradingArea[@"id"];
    }
    NSString *salary = @"";
    if (_desired_income) {
        salary = _desired_income[@"value"];
    }
    NSString *workingLife = @"";
    if (_working_life) {
        workingLife = _working_life[@"value"];
    }
    NSString *education = @"";
    if (_education) {
        education = _education[@"value"];
    }
    NSString *job_type = @"";
    if (_job_type) {
        job_type = _job_type[@"value"];
    }
    NSString *financingPhase = @"";
    if (_field) {
        financingPhase = _field[@"value"];
    }
    NSString *industryField = @"";
    if (_phase) {
        industryField = _phase[@"value"];
    }
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [HttpRequest PostrequestUrl:@"/recruit/positionList" Dic:@{@"pageNo":[NSString stringWithFormat:@"%ld",_pageNo],@"pageSize":@"10",@"area":area,@"salary":salary,@"workingLife":workingLife,@"education":education,@"job_type":job_type,@"financingPhase":financingPhase,@"industryField":industryField,@"name":_keyWord,@"city":[standfault objectForKey:@"cityID"]} completion:^(NSDictionary *responseDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([responseDic[@"success"] boolValue]) {
                    if (_datas.count < [responseDic[@"count"] integerValue]) {
                        [_datas addObjectsFromArray:responseDic[@"data"]];
                    }
                }else{
                    [TomamaUI creatAlertWithTarget:self message:responseDic[@"msg"] timeInterval:2];
                }
                [HudHelper hideHudToView:self.view];
                [_table reloadData];
                if ([_table.mj_header isRefreshing]) {
                    [_table.mj_header endRefreshing];
                }
                if ([_table.mj_footer isRefreshing]) {
                    if (_datas.count >= [responseDic[@"count"] integerValue]) {
                        [_table.mj_footer endRefreshingWithNoMoreData];
                    }else{
                        [_table.mj_footer endRefreshing];
                    }
                }
            });
        }];
    });
}

-(void)getJobDictValue
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [HttpRequest PostrequestUrl:@"/other/getJobDictValue" Dic:@{} completion:^(NSDictionary *responseDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([responseDic[@"success"] boolValue]) {
                    _jobDictValue = responseDic;
                }
            });
        }];
    });
}

-(void)getCompanyDictValue
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [HttpRequest PostrequestUrl:@"/other/getCompanyDictValue" Dic:@{} completion:^(NSDictionary *responseDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([responseDic[@"success"] boolValue]) {
                    _companyDictValue = responseDic;
                }
            });
        }];
    });
}

@end
